package com.realtyreg.service.validator;

import org.apache.commons.lang3.StringUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * Created by Petro 03.01.13 23:18
 */
@SuppressWarnings("unchecked")
public class EnumFieldValidator implements ConstraintValidator<EnumField, String> {
    private Class<? extends Enum> type;
    private String[] values;

    public void initialize(EnumField constraintAnnotation) {
        type = constraintAnnotation.type();
        values = constraintAnnotation.values();
    }

    public boolean isValid(String value, ConstraintValidatorContext context) {
        try {
            if (StringUtils.isEmpty(value))
                return false;
            
            if (type != Enum.class) {
                try {
                    Enum.valueOf(type, value);
                } catch (IllegalArgumentException ignore) {
                    return false;
                }
            }
            
            for (String legalValue : values) {
                if (value.equals(legalValue))
                    return true;
            }
        } catch (Exception ignore) {
            return false;
        }
        return false;
    }
}
